<template>
  <div class="extra-review-list">
    <a-card title="附加分审查列表">
      <template #extra>
        <a-button type="primary" @click="$router.push('/extra-review/submit')">
          提交申请
        </a-button>
      </template>

      <a-form layout="inline" class="search-form">
        <a-form-item label="审核状态">
          <a-select v-model:value="searchForm.status" placeholder="请选择" style="width: 150px" allow-clear>
            <a-select-option value="pending">待审核</a-select-option>
            <a-select-option value="approved">已通过</a-select-option>
            <a-select-option value="rejected">已拒绝</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="学生">
          <a-input v-model:value="searchForm.student" placeholder="学号/姓名" style="width: 200px" />
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">查询</a-button>
            <a-button @click="handleReset">重置</a-button>
          </a-space>
        </a-form-item>
      </a-form>

      <a-table 
        :columns="columns" 
        :data-source="dataSource" 
        :loading="loading"
        bordered 
        :pagination="pagination"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag v-if="record.status === 'approved'" color="green">已通过</a-tag>
            <a-tag v-else-if="record.status === 'pending'" color="orange">待审核</a-tag>
            <a-tag v-else color="red">已拒绝</a-tag>
          </template>
          <template v-if="column.key === 'picture'">
            <a-image :src="record.picture_url || record.picture" :width="50" v-if="record.picture_url || record.picture" />
            <span v-else>-</span>
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a @click="handleView(record)">查看</a>
              <a 
                v-if="canApproveRecord(record)" 
                @click="handleReview(record, 'approve')" 
                style="color: #52c41a;"
              >
                通过
              </a>
              <a 
                v-if="canApproveRecord(record)" 
                @click="handleReview(record, 'reject')" 
                style="color: #ff4d4f;"
              >
                拒绝
              </a>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 审核弹窗 -->
    <a-modal
      v-model:open="reviewModalVisible"
      :title="reviewAction === 'approve' ? '审核通过' : '审核拒绝'"
      @ok="handleSubmitReview"
      @cancel="handleCancelReview"
      :ok-text="reviewAction === 'approve' ? '通过' : '拒绝'"
      :ok-type="reviewAction === 'approve' ? 'primary' : 'danger'"
    >
      <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
        <a-form-item label="学生">
          {{ currentRecord?.student?.username || '-' }}
        </a-form-item>
        <a-form-item label="证书名称">
          {{ currentRecord?.name }}
        </a-form-item>
        <a-form-item label="级别">
          {{ currentRecord?.ranks }} - {{ currentRecord?.levels }}
        </a-form-item>
        <a-form-item label="审核级别" required>
          <a-select v-model:value="reviewLevel" placeholder="请选择审核级别">
            <a-select-option value="third">班委审核</a-select-option>
            <a-select-option value="second">辅导员审核</a-select-option>
            <a-select-option value="first">学工办审核</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item :label="reviewAction === 'approve' ? '备注' : '拒绝原因'" :required="reviewAction === 'reject'">
          <a-textarea
            v-model:value="reviewRemark"
            :placeholder="reviewAction === 'approve' ? '请输入审核备注（可选）' : '请输入拒绝原因（必填）'"
            :rows="4"
          />
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import { extraReviewAPI } from '@/api/extraReview'
import type { ExtraReview } from '@/api/extraReview'

const router = useRouter()
const loading = ref(false)
const dataSource = ref<ExtraReview[]>([])
const reviewModalVisible = ref(false)
const reviewAction = ref<'approve' | 'reject'>('approve')
const reviewLevel = ref<'first' | 'second' | 'third'>('third')
const reviewRemark = ref('')
const currentRecord = ref<ExtraReview | null>(null)

const searchForm = reactive({
  status: undefined as 'pending' | 'approved' | undefined,
  student: ''
})

const columns = [
  { title: 'ID', dataIndex: 'id', key: 'id', width: 70 },
  { title: '学生', dataIndex: 'student_name', key: 'student_name', width: 120 },
  { title: '证书名称', dataIndex: 'name', key: 'name' },
  { title: '级别', dataIndex: 'ranks', key: 'ranks', width: 100 },
  { title: '等级', dataIndex: 'levels', key: 'levels', width: 100 },
  { title: '分数', dataIndex: 'grade', key: 'grade', width: 80 },
  { title: '证书图片', key: 'picture', width: 80 },
  { title: '审核状态', key: 'status', width: 150 },
  { title: '操作', key: 'action', width: 150 }
]

const pagination = ref({
  total: 0,
  current: 1,
  pageSize: 10,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    pagination.value.current = page
    pagination.value.pageSize = pageSize
    loadData()
  }
})

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const res = await extraReviewAPI.getExtraReviewList({
      page: pagination.value.current,
      page_size: pagination.value.pageSize,
      status: searchForm.status
    })
    dataSource.value = res.data.results
    pagination.value.total = res.data.count
  } catch (error: any) {
    message.error('加载数据失败: ' + (error.response?.data?.message || error.message))
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.value.current = 1
  loadData()
}

// 重置
const handleReset = () => {
  searchForm.status = undefined
  searchForm.student = ''
  pagination.value.current = 1
  loadData()
}

// 判断记录是否可以审核
const canApproveRecord = (record: ExtraReview) => {
  // 如果全部审核都通过了，则不能再审核
  if (record.first_efficient && record.second_efficient && record.third_efficient) {
    return false
  }
  // 其他情况下，只要status是pending就可以审核
  return record.status === 'pending'
}

// 查看详情
const handleView = (record: ExtraReview) => {
  router.push(`/extra-review/detail/${record.id}`)
}

// 审核
const handleReview = (record: ExtraReview, action: 'approve' | 'reject') => {
  currentRecord.value = record
  reviewAction.value = action
  reviewLevel.value = 'third' // 默认班委审核
  reviewRemark.value = ''
  reviewModalVisible.value = true
}

// 提交审核
const handleSubmitReview = async () => {
  if (!currentRecord.value) return

  // 拒绝时必须填写原因
  if (reviewAction.value === 'reject' && !reviewRemark.value) {
    message.error('请输入拒绝原因')
    return
  }

  try {
    if (reviewAction.value === 'approve') {
      await extraReviewAPI.approveExtraReview(
        currentRecord.value.id,
        reviewLevel.value,
        reviewRemark.value || undefined
      )
      message.success('审核通过')
    } else {
      await extraReviewAPI.rejectExtraReview(
        currentRecord.value.id,
        reviewLevel.value,
        reviewRemark.value
      )
      message.success('已拒绝')
    }
    reviewModalVisible.value = false
    loadData() // 刷新列表
  } catch (error: any) {
    message.error('审核失败: ' + (error.response?.data?.message || error.message))
  }
}

// 取消审核
const handleCancelReview = () => {
  reviewModalVisible.value = false
  currentRecord.value = null
  reviewRemark.value = ''
}

onMounted(() => {
  loadData()
})
</script>

<style scoped>
.search-form {
  margin-bottom: 20px;
}
</style>
